package it.com.chen.movieReleasesDB;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Scanner;

public class FileDBReader {

	private static HashMap<Integer, DBEntry> ReleasesMovies = new HashMap<Integer, DBEntry>();
	
	public static ProgramData collectReleasedMovies() {
		
		int updateDate = 1;
		int updateMonth = 1;
		int updateYear = 2012;
		HashMap<Integer, DBEntry> db = new HashMap<>();
		
		Scanner lineScanner;
		try {
			// get the path of the input file
			File directory = new File(".");
			String canonicalPath = "";
			try {
				canonicalPath = directory.getCanonicalPath();
			} catch (Exception e) {
				System.out.println("*** ERROR *** Exception found: "
						+ e.getMessage());
			}
			String filePath = canonicalPath + "/db/data.dat";

			// read the contents of the input file and store values into vectors
			FileInputStream fstream = new FileInputStream(filePath);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String aLine;

			int dbCounter = 0;
			while ((aLine = br.readLine()) != null) {
				lineScanner = new Scanner(aLine);
				
				if(aLine.startsWith("last_update")){
					lineScanner.useDelimiter("\\s+");
				}else{
					lineScanner.useDelimiter("\\|");
				}
				
				if (lineScanner.hasNext()) {
					String info = lineScanner.next();
					if (info.startsWith("#")) {
						// do nothing if it's a comment line or a line about
						// program infos
					} else {
						if (info.startsWith("last_update")) {
							updateDate = Integer.parseInt(lineScanner.next().trim());
							updateMonth = Integer.parseInt(lineScanner.next().trim());
							updateYear = Integer.parseInt(lineScanner.next().trim());
						}else{
							String movieTitle = info.trim();
							int releaseDate = Integer.parseInt(lineScanner.next().trim());
							int releaseMonth = Integer.parseInt(lineScanner.next().trim());
							int releaseYear = Integer.parseInt(lineScanner.next().trim());
							String url = lineScanner.next().trim();
							DBEntry entry = new DBEntry(releaseDate, releaseMonth, releaseYear, movieTitle, url);
							db.put(dbCounter, entry);
							dbCounter++;
						}
					}
				}
			}
			in.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ProgramData programData = new ProgramData(db, updateDate, updateMonth, updateYear);
		return programData;

	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ProgramData programData = collectReleasedMovies();
		HashMap<Integer, DBEntry> db = programData.getDb();
		MovieListPrinter.print(db);
	}

}
